﻿using System.Security.Authentication;
using System.Text;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Extensions.WebSocket4Net;
using MQTTnet.Formatter;

namespace mqtt.test.client
{
    public static class Client_Connection_Samples
    {
      

        public static async Task Connect_Client_Using_MQTTv5()
        {
            /*
             * This sample creates a simple MQTT client and connects to a public broker using MQTTv5.
             * 
             * This is a modified version of the sample _Connect_Client_! See other sample for more details.
             */

            var mqttFactory = new MqttFactory();

            using var mqttClient = mqttFactory.CreateMqttClient();
            // Setup message handling before connecting so that queued messages
            // are also handled properly. When there is no event handler attached all
            // received messages get lost.
            mqttClient.ApplicationMessageReceivedAsync += e =>
            {
                Console.WriteLine("Received application message.");
                e.DumpToConsole();
                var str = Encoding.UTF8.GetString(e.ApplicationMessage.PayloadSegment);
                Console.WriteLine(str);

                return Task.CompletedTask;
            };

            var mqttClientOptions = new MqttClientOptionsBuilder()
                .WithTcpServer("127.0.0.1")
                .WithProtocolVersion(MqttProtocolVersion.V310)
                .Build();

            // In MQTTv5 the response contains much more information.
            var response = await mqttClient.ConnectAsync(mqttClientOptions, CancellationToken.None);



      /*      var applicationMessage = new MqttApplicationMessageBuilder()
         .WithTopic("samples/temperature/living_room")
         .WithPayload("19.5")
         .Build();

            await mqttClient.PublishAsync(applicationMessage, CancellationToken.None);




            var mqttSubscribeOptions = mqttFactory.CreateSubscribeOptionsBuilder()
            .WithTopicFilter(
                f =>
                {
                    f.WithTopic("mqttnet/samples/topic/2");
                })
            .Build();

            var res = await mqttClient.SubscribeAsync(mqttSubscribeOptions, CancellationToken.None);
            res.DumpToConsole();
*/
            Console.WriteLine("Press enter to exit.");
            Console.ReadLine();
        }

    

     
    }
}
